//
//  WebView_JS.m
//  Project_Demo
//
//  Created by sisi on 2018/7/11.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

#import "XZ_WebView_JS.h"
#import "baseview.h"

@interface XZ_WebView_JS ()<WKNavigationDelegate,UIScrollViewDelegate,WKUIDelegate,WKScriptMessageHandler>
//@property(nonatomic,strong)WKWebView *mainWebView;
//@property(nonatomic,strong)UIButton *alertButton;

@property(nonatomic,strong)UIButton *alertButton;

@end

@implementation XZ_WebView_JS

- (UIButton *)alertButton{
    
    if (_alertButton == nil) {
        _alertButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth*0.2, kScreenHeight - 60, kScreenWidth * 0.6, 40)];
        _alertButton.backgroundColor = [UIColor colorWithRed:250/255.0 green:204/255.0 blue:96/255.0 alpha:1.0];
        _alertButton.layer.cornerRadius = 6.0f;
        _alertButton.layer.masksToBounds = YES;
        _alertButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_alertButton setTitle:@"弹出弹窗" forState:UIControlStateNormal];
        [_alertButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_alertButton addTarget:self action:@selector(alertButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _alertButton;
}


- (void)alertButtonAction{
    [self.mainWebView evaluateJavaScript:@"iOSCallJsAlert()" completionHandler:^(id _Nullable item, NSError * _Nullable error) {
        NSLog(@"alert===>%@",item);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self showWebViewWith:nil localHtml:@"index.html" jsActionNameArr:@[@"currentCookies",@"jsToOcAction"]];
    [self.view addSubview:self.alertButton];

    self.JSActionBlock = ^(NSString *name,id body) {
        NSLog(@"name==>%@,body==>%@",name,body[@"body"]);
    };
    
//    NSString *title = [NSString stringWithFormat:@"<div>%@</div>",@"123123"];
//    NSString *url = [NSString stringWithFormat:@"<html><head></head><body>%@</body></html>",title];
//
//    [self.mainWebView loadHTMLString:url baseURL:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS调用alert" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"%@", message);
}

@end
